<!--
 - upload_score.php
 - This form insert a score record into the MySql database. 
 - 
 - 
 - Revision History: 
 -  
 - Date     Author       Version   Changes
 - ======== ============ ========= ================================================================
 - 03/21/10 Steve Hu     2.0       Initial version.
 - 03/27/10 Steve Hu	 2.1	   Added record exist checking. Insert a record only if it is a new
 -                                 one.
 - ======== ============ ========= ================================================================
 -
 -->

<?
	/* Setup database connection.  */
	include("./sigma_dataconn.php");

	/* Score data retrieved from iphone device.  */
	$username = $_POST['UserName'];
	$score = $_POST['Score'];
	$sql = "SELECT COUNT(*) AS RecordNum FROM score_data WHERE UserName = '$username' AND Score = $score";
	$result = mysql_query($sql, $connection) or die( "Could not execut sql: $sql");

	$row = mysql_fetch_array($result);
	$ScoreExist = $row["RecordNum"] ;
	
	/* Only insert score to database if the record doesn reside in database.  */
	if ($ScoreExist == 0)
	{
		/* Increment the scoreID.  */
		$sql = "SELECT Max(ScoreID) AS currentid FROM score_data";
		$result = mysql_query($sql, $connection) or die( "Could not execut sql: $sql");

		$row = mysql_fetch_array($result);
		$nextid = $row["currentid"] ;
		$nextid++;

		/* Insert the score record into the score_data table.  */
		$sql = "INSERT INTO score_data (ScoreID, UserName, Score, Date) ";
		$sql = $sql . "VALUES ('$nextid', '$username', '$score', CURDATE()) ";

		/* Redirect to top score page if inserted successfully.  */
		$res = mysql_query($sql, $connection) or die( "Could not execut sql: $nextid:  $sql");
		if ( !$res ) 
		{
			echo "problem inserting to database";
		} 
		else 
		{
			mysql_close($connection);
			header( "Location: ./top_scores.php" );
		}
	}
	else
	{
		mysql_close($connection);
		header( "Location: ./top_scores.php" );
	}
?>